using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Models;
using GameView.Services;
using GameView.Services.Comment;
using GameView.Services.Dtos.Blacklist;
using GameView.Services.Dtos.Project;
using GameView.Views;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;

namespace GameView.ViewModels
{
    public partial class CommandAddViewModel : ObservableValidator
    {
        private List<ProjectWithGamesInfo> _projectWithGamesInfos;
        private readonly CommandService _service;

        private readonly ProjectService _projectService;

        public CommandAddViewModel(CommandService service, ProjectService projectService)
        {
            _service = service;
            _projectService = projectService;
            IsMerchant = StaticValues.LoginInfo.PersonInfo.RoleId != 3;
            LoadPG().ConfigureAwait(false);
        }

        [ObservableProperty]
        private bool _isLoading = false;

        [ObservableProperty]
        private ObservableCollection<TreeNode> _nodes = [];

        [ObservableProperty]
        [NotifyDataErrorInfo]
        [Required(ErrorMessage = "选择项目")]
        [NotifyCanExecuteChangedFor(nameof(AddNewCommand))]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        private TreeNode? _selectedNode;

        [ObservableProperty]
        private bool _isAddnew = false;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        private string _projectName = string.Empty;

        [ObservableProperty]
        [Required(ErrorMessage = "指令代码不能为空")]
        [Range(1, 999999999, ErrorMessage = "指令代码必须为数字")]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        private int? _commandCode = null;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        private string _commandStr = string.Empty;

        [ObservableProperty]
        private string _remark = string.Empty;

        [ObservableProperty]
        private ObservableCollection<CommandShowModel> _commandOptions;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        [Required(ErrorMessage = "指令不能为空")]
        private CommandShowModel _selectedCommand;

        [ObservableProperty]
        private int _id = 0;

        [ObservableProperty]
        private bool _isMerchant = true;

        [RelayCommand]
        private async Task RefreshList()
        {
            await LoadPG();
        }

          partial void OnSelectedNodeChanged(TreeNode value)
        {
            if (value is null)
                return;
            ProjectName = value.Name;
            LoadCommand(ProjectName).ConfigureAwait(false);
            SelectedNode = value;
            if (SelectedNode.Status == 6002)
            {
                GlobalMessage.Instance.ShowWarning($"{SelectedNode.Name}已经离线，无法操作！");
                return;
            }
        }

        [RelayCommand]
        private async Task Edit(CommandShowModel value)
        {
            if (value == null)
                return;
            ProjectName = value.NameEn;
            CommandCode = value.CValue;
            CommandStr = value.NameCn;
            Remark = value.Remark;
            Id = value.Id;
            IsAddnew = true;
            SelectedCommand = value;
            await Task.CompletedTask;
        }

        [RelayCommand]
        private async Task Delete(CommandShowModel value)
        {
            if (value == null)
                return;
            var view = new MsgViewDialogView("警告", 3002, "您确认要删除指令", value.NameCn, "的数据吗？");
            view.SetPP("CommDialog");
            var resxx = await ExtentHelper.GetService<IDialogService>().ShowDialog(view, "CommDialog");
            if (!(bool)resxx)
                return;
            var res = await _service.BatchDelete([value.Id]);
            if (res == null)
            {
                GlobalMessage.Instance.ShowError($"网络异常请稍后核查充值结果！");
            }
            if (res.StatusCode == 200)
            {
                await LoadCommand(SelectedNode.Name);
            }
            else
            {
                GlobalMessage.Instance.ShowError($"操作失败：{res.Errors}");
            }
        }

        [RelayCommand(CanExecute = nameof(CanAddNew))]
        private async Task AddNew()
        {
            await Task.CompletedTask;
            IsAddnew = true;
        }

        [RelayCommand]
        private async Task Cancel()
        {
            await Task.CompletedTask;
            IsAddnew = false;
        }

        [RelayCommand(CanExecute = nameof(CanSubmit))]
        private async Task Submit()
        {
            ApiResponse<CommandShowModel> res = null;
            if (Id > 0)
            {
                var dtoEdit = new CommandEditDto()
                {
                    Id = Id,
                    CValue = CommandCode.Value,
                    NameCn = CommandStr,
                    NameEn = ProjectName,
                    Remark = Remark,
                };
                res = await _service.Edit(dtoEdit);
            }
            else
            {
                var dtoAdd = new CommandAddDto()
                {
                    CValue = CommandCode.Value,
                    NameCn = CommandStr,
                    NameEn = ProjectName,
                    Remark = Remark,
                };
                res = await _service.Add(dtoAdd);
            }
            if (res == null)
            {
                GlobalMessage.Instance.ShowError($"网络异常请稍后核查充值结果！");
                return;
            }
            if (res.StatusCode == 200)
            {
                await LoadCommand(SelectedNode.Name);
                CommandCode = 0;
                CommandStr = "";
                IsAddnew = false;
                Id = 0;
            }
            else
            {
                GlobalMessage.Instance.ShowError($"操作失败：{res.Errors}");
            }
        }

        private async Task LoadCommand(string pName)
        {
            IsLoading = true;
            CommandOptions ??= [];
            CommandOptions.Clear();
            var res = await _service.GetListAsync(pName);
            if (res.StatusCode != 200)
            {
                GlobalMessage.Instance.ShowError(JSON.Serialize(res.Errors));
                return;
            }
            foreach (var item in res.Data)
            {
                CommandOptions.Add(item);
            }
            IsLoading = false;
        }

        private async Task<bool> LoadPG()
        {
            try
            {
                IsLoading = true;
                ApiResponse<List<ProjectWithGamesInfo>> res = null;
                if (StaticValues.LoginInfo.PersonInfo.RoleId != 1)
                    res = await _projectService.GetByPersonIdHAsync();
                else
                    res = await _projectService.GetAllHAsync();
                if (res.Data.IsNullOrEmpty())
                    return false;
                _projectWithGamesInfos = res.Data;
                Nodes.Clear();

                foreach (var data in _projectWithGamesInfos)
                {
                    var p = new TreeNode() { IsParent = true, Id = data.Id, Name = data.Name, Type = 0 };
                    Nodes.Add(p);
                }

                return true;
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"操作失败：{ex.Message}");
                return false;
            }
            finally
            {
                IsLoading = false;
            }
        }

        private bool CanSubmit() => !HasErrors && !ProjectName.IsNullOrEmpty() && !CommandStr.IsNullOrEmpty() && CommandCode > 0;

        private bool CanDelete() => !HasErrors && SelectedNode != null && SelectedNode.Parent != null && SelectedCommand != null;

        private bool CanAddNew() => SelectedNode != null;
    }
}